#include "shell.h"
#include "string.h"


void shellPrint(char* s, ...)
{
	static const char DEC[] = "0123456789\0";
	static const char HEX[] = "0123456789abcdef\0";
	va_list ap;
	char* zeiger;
	int i;
	int j;
	int k;
	char buffer[16];
	int length = stringLaenge(s);

	// Variable Parameterliste initialisieren
	va_start(ap, s);

	for(i = 0; i < length; i++)
	{
		if(s[i] == '%' && i < length-1)
		{
			i++;
			switch(s[i])
			{
				case '%':
				   printChar('%');
				   break;

				case 's':
				   break;

				
				case 'd':
				   j = va_arg(ap, int);
				   if(j < 0)
				   {
					printChar('-');
				   }
				   for(k = 15; k && j ; --k)
				   {
					buffer[k] = DEC[j % 10];
					j /= 10;
				   }
				   for(; k < 15; printChar(buffer[++k]));
				   break;

				case 'c':
				   printChar(va_arg(ap, char));
				   break;

				case 'x':
				   j = va_arg(ap, int);
				   for(k = 15; k && j; --k)
				   {
					buffer[k] = HEX[j % 16];
					j /= 16;
				   }
				   shellPrint("0x");
				   for(; k < 15; printChar(buffer[++k]));
				   break;

				default:
				   printChar(s[i]);
				   break;
			}
		}
		else
		{
			printChar(s[i]);
		}
		 
	}
	va_end(ap);

}

void clearShell(void)
{
	int i;
	
	// i < 2000, da 4096 Bytes
	// nur jedes 2te Zeichen geändert, da Rest Farbe
	for(i = 0;i < 2000; i++)
	{
		videoMem[i * 2] = 0x20;
	}
}

void printChar(char zeichen)
{
	videoMem[position * 2] = zeichen;
	
	if(position == 1999)
	{
		clearShell();
		position = 0;
	}
	else
	{
		position++;
	}	
	if(zeichen == '\n')
	{
		if(position > 1920)
		{
			clearShell();
			position = 0;
		}
		else
		{
			removeCursor((position-1) * 2);
			int linie = position / 80;
			int differenz = (linie + 1) * 80 - position;
			position = position + differenz;
		}
		
	}
	
	setCursor(position * 2);
	
}

void setCursor(int pos)
{
	videoMem[pos] = 0x5F;
}

void removeCursor(int pos)
{
	videoMem[pos] = 0x20;
}

void removeChar()
{
	if(position == 0 || position % 80 == 0)
	{
		
	}
	else
	{
		position--;
		videoMem[position * 2] = 0x20;
		removeCursor((position + 1) * 2);
		setCursor(position * 2);
	}
	
}

void commandEnter()
{
	char zeile[80];
	char* kommando;
	char attribut[80];
	
	int startPos = getLinie() * 80;
	
	printChar('\n');	

	int i;
	for(i = 0; i < 80; i++)
	{
		zeile[i] = videoMem[(startPos + i) * 2];
	}	
		
	// String trennen
	kommando = splitString(' ', zeile);
	
	//printChar('\n');

	shellPrint("Kommando: ");
	shellPrint(kommando);
	
	// Zeilensprung machen
	printChar('\n');
	
	
	// Kommando ausführen :D
	if(vergleicheStrings(kommando, "time\0") == 1)
	{
		commandTime();
		return;
	}
	
	if(vergleicheStrings(kommando, "convert\0") == 1)
	{
		commandConvert(57, 2);
		return;
	}
	
	shellPrint("Kommando nicht erkannt! Bitte neu versuchen :)\n");
	
}

int getLinie()
{
	return position/80;
}
